package org.tgcloud.group.core.custom;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.DateUtil;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.core.session.Session;
import org.tgcloud.group.core.session.SessionFactory;
import org.tgcloud.group.entity.*;
import org.tgcloud.group.repository.*;
import org.tgcloud.group.web.exception.NeedLoginException;
import org.tgcloud.group.web.exception.NeedPermissionAspectException;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Author SGY
 * @Date 2020/10/15 17:53
 * @Description // 自定义AOP，拦截权限注解
 **/
@Slf4j
@Component
@Aspect
public class PermissionAspect implements Ordered {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private LogInfoMapper logInfoMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysManagerUserMapper managerUserMapper;

    @Autowired
    private MjBusinessPersonMapper businessPersonMapper;


    // 切点
    @Pointcut("@annotation(org.tgcloud.group.core.custom.Permissions)")
    public void permissions() {
    }


    @Around("permissions()")
    public Object doPermission(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Permissions myPermission = method.getAnnotation(Permissions.class);
        if (myPermission == null) {
            return joinPoint.proceed();
        }

        String permissions = myPermission.value();
        if (StringUtil.isBlank(permissions)) {
            return joinPoint.proceed();
        }

        // 获取请求信息
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getParameter("token");
        if (StringUtil.isBlank(token)) {
            return APPResultMessage.NO_LOGIN();
        } else {
            Session session = sessionFactory.getSession(token);
            if (session == null) {
                return APPResultMessage.NO_LOGIN();
            } else {
                /*权限判断、角色判断*/
                LogInfo logAccountLogin = logInfoMapper.selectByToken(token);
                if (logAccountLogin == null || logAccountLogin.getStatus() != 1) {
                    sessionFactory.destroySession(token);
                    return APPResultMessage.NO_LOGIN();
                }

                int userId = session.getUserId();
                short userType = session.getUserType();

                if (userType == 3){
                    MjBusinessPerson businessPerson = businessPersonMapper.selectByPrimaryKey(userId);
                    if (businessPerson == null || businessPerson.getStatus() == 10){
                        return APPResultMessage.NO_LOGIN();
                    }
                }else {
                    // 判断用户状态
                    SysManagerUser user = managerUserMapper.selectByPrimaryKey(userId);
                    if (user == null || user.getStatus() != 1) {
                        return APPResultMessage.NO_LOGIN();
                    }
                    // 判断角色状态
                    String[] split = user.getRoleId().split(",");
                    boolean noLoginStatus = true;
                    for (String roleId : split){
                        SysRole sysRole = sysRoleMapper.selectByPrimaryKey(Integer.valueOf(roleId));
                        if (sysRole != null && sysRole.getStatus() == 1) {
                            noLoginStatus = false;
                        }
                    }
                    if (noLoginStatus){
                        return APPResultMessage.NO_LOGIN();
                    }
                }

                String p = "";
                // 判断是否需要数据权限
                String[] split = permissions.split(",");
                int j = 0;
                int i = 0;
                for (int x=0;x<split.length;x++) {
                    String permiss = split[x];
                    p = permiss;
                    if (userType == 3){
                        // 角色是否包含该权限
                        int rl = sysPermissionMapper.selectRoleIsPermissionByBusiness(userId, permiss);
                        if (rl > 0) {
                            i = rl;
                            break;
                        }
                        // 用户是否包含该权限
//                        int ul = sysPermissionMapper.selectUserIsPermissionByUserId(userId, permiss);
//                        if (ul > 0) {
//                            j = ul;
//                            break;
//                        }
                    }else {
                        // 角色是否包含该权限
                        int rl = sysPermissionMapper.selectRoleIsPermissionByUserId(userId, permiss);
                        if (rl > 0) {
                            i = rl;
                            break;
                        }
                        // 用户是否包含该权限
                        int ul = sysPermissionMapper.selectUserIsPermissionByUserId(userId, permiss);
                        if (ul > 0) {
                            j = ul;
                            break;
                        }
                    }
                }
                if (i == 0 && j == 0) {
                    throw new NeedPermissionAspectException();
                } else {
                    SysPermission permission = sysPermissionMapper.selectMsgByPermission(p);
                    if (permission == null){
                        log.error("暂未找到该权限");
                        throw new NeedPermissionAspectException();
                    }

                    return joinPoint.proceed();
                }
            }
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
